import dayjs from "dayjs";
import editForm from "../form.vue";
import { message } from "@/utils/message";
import { ElMessageBox } from "element-plus";
import { usePublicHooks } from "@/views/system/hooks";
import { addDialog } from "@/components/ReDialog";
import type { FormItemProps } from "./types";
import type { PaginationProps } from "@pureadmin/table";
import { getKeyList, deviceDetection } from "@pureadmin/utils";
import { waAccountApi, type WaAccountForm, type SearchParams } from "@/api/whatsapp";
import { type Ref, reactive, ref, onMounted, h, toRaw } from "vue";

export function useWaAccount(tableRef: Ref) {
  const form = reactive<SearchParams>({
    wa_account: "",
    admin_user_id: undefined,
    remark: "",
    status: 1,  // 默认只显示正常状态
    is_drainage: undefined
  });

  const formRef = ref();
  const dataList = ref([]);
  const userList = ref([]);
  const loading = ref(true);
  const switchLoadMap = ref({});
  const { switchStyle, tagStyle } = usePublicHooks();
  const selectedNum = ref(0);

  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 20,
    pageSizes: [20, 40, 60, 100, 300, 500],
    currentPage: 1,
    background: true
  });

  const columns: TableColumnList = [
    // {
    //   label: "勾选列",
    //   type: "selection",
    //   fixed: "left",
    //   reserveSelection: true
    // },
    {
      label: "编号",
      prop: "id",
      width: 90
    },
    {
      label: "WhatsApp账号",
      prop: "wa_account",
      width: 150,
      showOverflowTooltip: true
    },
    {
      label: "使用者",
      prop: "admin_user_name",
      width: 120,
      showOverflowTooltip: true
    },
    {
      label: "备注",
      prop: "remark",
      width: 150,
      showOverflowTooltip: true
    },
    {
      label: "创建者",
      prop: "creator_name",
      minWidth: 100
    },
    {
      label: "账号状态",
      prop: "status_text",
      minWidth: 90,
      cellRenderer: scope => (
        <el-tag
          size={scope.props.size === "small" ? "small" : "default"}
          type={scope.row.status === 1 ? "success" : "danger"}
          style={tagStyle.value(scope.row.status === 1 ? 1 : 0)}
        >
          {scope.row.status_text}
        </el-tag>
      )
    },
    {
      label: "应用引流",
      prop: "is_drainage_text",
      minWidth: 90,
      cellRenderer: scope => (
        <el-tag
          size={scope.props.size === "small" ? "small" : "default"}
          type={scope.row.is_drainage ? "success" : "info"}
          style={tagStyle.value(scope.row.is_drainage ? 1 : 0)}
        >
          {scope.row.is_drainage_text}
        </el-tag>
      )
    },
    {
      label: "创建时间",
      prop: "created_at",
      minWidth: 160
    },
    {
      label: "更新时间",
      prop: "updated_at",
      minWidth: 160
    },
    {
      label: "操作",
      fixed: "right",
      width: 240,
      slot: "operation"
    }
  ];

  function handleSelectionChange(val) {
    selectedNum.value = val.length;
  }

  function resetForm(formEl) {
    if (!formEl) return;
    formEl.resetFields();
    // 重置后默认显示正常状态的账号
    form.status = 1;
    onSearch();
  }

  async function onSearch() {
    loading.value = true;
    const params = {
      ...toRaw(form),
      page: pagination.currentPage,
      limit: pagination.pageSize
    };

    try {
      const { data } = await waAccountApi.list(params);
      dataList.value = data.data;  // Laravel分页结构中数据在data.data中
      pagination.total = data.total;
      pagination.currentPage = data.current_page;
      pagination.pageSize = data.per_page;
      userList.value = data.user_list || [];
    } catch (error) {
      console.error("获取账号列表失败:", error);
      message("获取账号列表失败", { type: "error" });
    } finally {
      loading.value = false;
    }
  }

  function handleSizeChange(val: number) {
    pagination.pageSize = val;
    onSearch();
  }

  function handleCurrentChange(val: number) {
    pagination.currentPage = val;
    onSearch();
  }

  function chores(curData, res, title, done) {
    if (res.code === 0) {
      message(`您${title}了账号${curData.wa_account}`, {
        type: "success"
      });
      done(); // 关闭弹框
      onSearch(); // 刷新表格数据
    } else {
      message(`${title}失败，原因：${res.message}`, {
        type: "error"
      });
    }
  }

  function openDialog(title = "新增", row?: FormItemProps) {
    addDialog({
      title: `${title}WhatsApp账号`,
      props: {
        formInline: {
          wa_account: row?.wa_account ?? "",
          admin_user_id: row?.admin_user_id ?? undefined,
          remark: row?.remark ?? "",
          is_drainage: row?.is_drainage ?? false,
          status: row?.status ?? 1,
          userList: userList.value
        }
      },
      width: "46%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef, formInline: null }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as WaAccountForm;

        FormRef.validate(valid => {
          if (valid) {
            // 只提取需要的字段，过滤掉userList等不必要的数据
            const submitData = {
              wa_account: curData.wa_account,
              admin_user_id: curData.admin_user_id,
              remark: curData.remark,
              is_drainage: curData.is_drainage,
              status: curData.status
            };

            if (title === "新增") {
              waAccountApi.create(submitData).then(res => chores(curData, res, title, done));
            } else {
              waAccountApi.update(row.id, submitData).then(res => chores(curData, res, title, done));
            }
          }
        });
      }
    });
  }

  async function handleDelete(row) {
    try {
      const result = await ElMessageBox.confirm(
        `确认要删除账号"${row.wa_account}"吗？`,
        "删除确认",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      );

      if (result === "confirm") {
        const res = await waAccountApi.delete(row.id);
        if (res.code === 0) {
          message(`删除账号"${row.wa_account}"成功`, { type: "success" });
          onSearch();
        } else {
          message(`删除失败，${res.message}`, { type: "error" });
        }
      }
    } catch (error) {
      console.log("用户取消删除");
    }
  }

  async function handleEnable(row) {
    try {
      const action = row.deleted_at > 0 ? "启用" : "禁用";
      const result = await ElMessageBox.confirm(
        `确认要${action}账号"${row.wa_account}"吗？`,
        `${action}确认`,
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      );

      if (result === "confirm") {
        const res = await waAccountApi.enable(row.id);
        if (res.code === 0) {
          message(res.data.message || `${action}成功`, { type: "success" });
          onSearch();
        } else {
          message(`${action}失败，${res.message}`, { type: "error" });
        }
      }
    } catch (error) {
      console.log("用户取消操作");
    }
  }

  async function handleBatchDelete() {
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
    if (curSelected.length === 0) {
      message("请先选择要删除的账号", { type: "warning" });
      return;
    }

    try {
      const result = await ElMessageBox.confirm(
        `确认要删除选中的 ${curSelected.length} 个账号吗？`,
        "批量删除确认",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      );

      if (result === "confirm") {
        let successCount = 0;
        let errorCount = 0;

        for (const item of curSelected) {
          try {
            const res = await waAccountApi.delete(item.id);
            if (res.code === 0) {
              successCount++;
            } else {
              errorCount++;
            }
          } catch (error) {
            errorCount++;
          }
        }

        message(`批量删除完成：成功${successCount}个，失败${errorCount}个`, {
          type: successCount > 0 ? "success" : "error"
        });
        onSearch();
      }
    } catch (error) {
      console.log("用户取消批量删除");
    }
  }

  onMounted(() => {
    onSearch();
  });

  return {
    form,
    loading,
    columns,
    dataList,
    userList,
    pagination,
    selectedNum,
    switchLoadMap,
    switchStyle,
    onSearch,
    resetForm,
    openDialog,
    handleDelete,
    handleEnable,
    handleBatchDelete,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange
  };
}
